<template>
  <div style="padding: 30px">
    <!--<div style="padding: 15px 0;font-weight: bold;">当前门店ID：{{merchant_id}}</div>-->
    <el-form  :label-position="'left'" label-width="150px" style="padding-bottom: 30px;">
      <div class="contentFist">
        <div>
          <div class="title">
            <!--<span class="spanNum">1</span>-->
            <span>上传Excel文件</span>
          </div>
          <div class="detail">
            <div>-如已经准备好文件，请直接上传文件</div>
            <div>-如有检测到数据异常，请修改后再次重新上传</div>
            <div>
              -如未有模板文件，请先
              <a href="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/excel/%E5%AF%BC%E5%85%A5%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xlsx">
                <el-button style="margin: 0 5px" size="mini" type="primary">下载模板</el-button>
              </a>
              ，填写数据后再上传文件
            </div>
          </div>
          <el-upload
            class="upload-demo"
            name="file"
            :action="$api.UPLOAD_EXCEL"
            :on-success="handleSuccess"
            :file-list="filelist"
            :disabled="isCheckExcel"
            :limit="999">
            <el-button :loading="isCheckExcel" size="medium" :type="!isCheckExcel&&errorMsgList!=''&&successMsg==''?'success':'primary'" @click="filelist=[]">{{isCheckExcel?'正在检测数据是否有误...':errorMsgList!=''&&successMsg==''?'更新':'上传'}}</el-button>
            <!--<div slot="tip" class="el-upload__tip">※ 注意：上传Excel文件</div>-->
          </el-upload>
          <!--<div class="title" style="margin-top: 40px">
            <span class="spanNum">2</span>
            <span>先下载excel导入模板，填写后再上传文件</span>
          </div>
          <div class="detail">
            <div>-请先下载模板，然后按照模板要求填写数据后再上传文件</div>
          </div>
          <a href="https://rzkeji.oss-cn-shenzhen.aliyuncs.com/web/yaojike2020/excel/goods.xlsx">
            <el-button style="margin-top: 15px" type="primary" size="medium">下载模板</el-button>
          </a>-->
        </div>
      </div>
      <div v-if="errorMsgList!='' && successMsg ==''">
        <div style="text-align: center;font-size: 20px;margin-top: 20px;margin-bottom: 10px;">异常信息</div>
        <el-table :data="errorMsgListTable" :header-cell-style="{background:'#eef1f6',color:'#DD0000'}" border style="color: #DD0000;">
          <!--<el-table-column align="center" prop="0" label="行号" />
          <el-table-column align="center" prop="message" label="排序" />-->
          <el-table-column align="center" label="检测结果">
            <template slot-scope="scope">
              {{scope.row}}
            </template>
          </el-table-column>
        </el-table>
        <div class="page-code" style="margin-top: 10px">
          <el-pagination
            background :current-page="errorPage" :page-size="errorLimit" layout="prev, pager, next" :total="errorTotal" @current-change="errorPageChange">
          </el-pagination>
        </div>
      </div>
      <div v-if="errorMsgList=='' && successMsg !=''" style="text-align: center;">
        <div style="margin-top: 20px;margin-bottom: 20px;font-size: 18px;">{{successMsg}}，请确定导入</div>
        <div>
          <el-button :loading="isImportGoodsLoading==true" size="mini" type="primary" @click="importGoods">
            {{isImportGoodsLoading!=3?isImportGoodsLoading==true?'正在导入':'确认导入':'导入成功'}}
          </el-button>
        </div>
        <div class="message" style="margin-top: 20px">
          <el-table
            :data="[uploadSuccessNoticeMsg]"
            border
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            style="width: 100%">
            <el-table-column prop="firstClassifyAddNum" label="一级分类增加数量" width="180"></el-table-column>
            <el-table-column prop="secondClassifyAddNum" label="二级分类增加数量" width="180"></el-table-column>
            <el-table-column prop="medicineAddNum" label="药品新增数量"></el-table-column>
            <el-table-column prop="medicineChangeNum" label="修改的商品数量"></el-table-column>
            <el-table-column prop="noneSystemMedicineNum" label="非平台商品库的商品数量"></el-table-column>
            <el-table-column prop="standardSystemMedicineNum" label="平台商品库的商品数量"></el-table-column>
          </el-table>
        </div>

        <div style="margin-top: 15px">
          <el-collapse v-model="collapseActiveNames">
            <el-collapse-item title="非商品库商品列表，此列表的数据不支持导入" name="1">
              <!--<download-excel
                v-show="noneSystemMedicineList&&noneSystemMedicineList.length>0"
                class = "export-excel-wrapper"
                :data = "exportNoneSystemMedicineList"
                :fields = "json_fields"
                name = "非商品库商品列表.xls">
                <el-button type="primary" size="small"style="margin-bottom: 10px">导出EXCEL</el-button>
              </download-excel>-->
              <!--<export-excel-common></export-excel-common>-->
              <el-button type="primary"size="small"style="margin-bottom: 10px" @click="output">导出EXCEL</el-button>
              <el-table
                :data="noneSystemMedicineList"
                id="mytable"
                ref="multipleTable"
                border
                :header-cell-style="{background:'#eef1f6',color: '#333333'}"
                style="width: 100%;align-items: center">
                <el-table-column prop="row" label="行数"></el-table-column>
                <el-table-column prop="upc" label="UPC"></el-table-column>
                <el-table-column prop="store" label="门店"></el-table-column>
                <el-table-column prop="first_classify" label="一级分类"></el-table-column>
                <el-table-column prop="second_classify" label="二级分类"></el-table-column>
                <el-table-column prop="selling_prise" label="售价"></el-table-column>
                <el-table-column prop="stock" label="库存"></el-table-column>
                <el-table-column prop="is_shop" label="状态"></el-table-column>
                <el-table-column prop="sort" label="排序"></el-table-column>
              </el-table>
            </el-collapse-item>
            <el-collapse-item style="color: red" title="新增一级分类数据" name="2">
              <div>
                <div v-if="firstClassifyAdd.length>10">
                  <span v-for="(item,index) in firstClassifyAdd" :key="index">{{item}}{{firstClassifyAdd.length!=index+1?'，':''}}</span>
                </div>
                <span v-else>无</span>
              </div>
            </el-collapse-item>
            <el-collapse-item title="新增二级分类数据" name="3">
              <div>
                <div v-if="secondClassifyAdd.length>0">
                  <span v-for="(item,index) in secondClassifyAdd" :key="index">{{item}}{{secondClassifyAdd.length!==index+1?'，':''}}</span>
                </div>
                <span v-else>无</span>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

      </div>
    </el-form>

    <!--<div class="upload-process-btn">
      <el-dropdown :trigger="'click'" class="">
        <div>
          <div class="tip" ref="importProgress" style="">导入进度</div>
        </div>
        <el-dropdown-menu slot="dropdown">
          <div style="padding-bottom: 10px;padding-left: 10px">
            <span style="color: grey;font-weight: bold">状态：</span>
            <span style="color: #333333;font-weight: bold;">{{status_name&&status_name!=='导入失败'?status_name:''}}</span>
          </div>
          <div class="upload-process-container">
            <div class="head-container">
              <div class="head-left">
                <span>导入进度</span>
                <span>（{{progress.now?progress.now:0}}/{{progress.total?progress.total:0}}）</span>
                </div>
              </div>
              <div class="message-list">
                <div class="message-item">
                  <el-progress style="margin-top: 10px" :text-inside="true" :stroke-width="26"
                               :percentage="progress.total?parseInt(progress.now/progress.total*100):0"></el-progress>
                </div>
              </div>
            </div>
          </el-dropdown-menu>
        </el-dropdown>
      </div>-->

  </div>
</template>

<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  export default {
    data() {
      return{
        merchant_id: '',
        importGoodsId:"",
        successMsg:"",
        errorMsgList:[],
        filelist:[],
        errorMsgListTable:[],
        isCheckExcel: false,
        errorPage: 1,
        errorTotal: 0,
        errorLimit: 8,
        isImportGoodsLoading: false,
        uploadSuccessNoticeMsg: '',
        processDialog: false,
        excel_check_id: '',
        interval: '',
        progress: '',
        isShowUpload: false,
        status_name: '',
        collapseActiveNames: ['1'],
        firstClassifyAdd: [], //新增一级分类列表
        noneSystemMedicineList: [], //非平台库商品列表
        exportNoneSystemMedicineList: [],//导出非平台库商品列表
        secondClassifyAdd: [], //新增二级分类列表
        json_fields: {
          /*'行数': 'row',*/
          'bar_code': 'upc',
          'store': 'store',
          'first_classify': 'first_classify',
          'second_classify': 'second_classify',
          'selling_price': 'selling_prise',
          'stock': 'stock',
          'is_shop': 'is_shop',
          'sort': 'sort'
        }
      }
    },
    created() {
      this.merchant_id = this.$route.query.merchant_id
    },
    mounted() {
      /*this.$store.state.uploadGoodsShow = true //进入这个页面时展示全局的上传进度框*/
    },
    destroyed() {
      clearInterval(this.interval)
      /*this.$store.state.uploadGoodsShow = true*/
    },
    methods: {

      //上传Excel文件
      handleSuccess(response, file, fileList) {
        if(response.level==='success'){
          this.importGoodsId = response.data.id
          this.importGoodsByRetrieval(response.data.id)
        } else {
          this.$message.error(response.message)
        }
      },
      showUploadExcelDialog(){
        this.uploadExcelDialog = true
        this.importGoodsId = ""
        this.successMsg = ""
        // this.showuploadBtn = true
        this.errorMsgList = []
        this.errorMsgListTable = []
        this.filelist = []
      },

      //检测Excel文件是否合格
      async importGoodsByRetrieval(id) {
        this.isCheckExcel = true
        let params = {
          excel_id: id,
          merchant_id: this.merchant_id
        }
        const res = await this.$api.checkExcel(params).then(res=>{
          if(res.data.level=='success'){
            this.successMsg = res.data.message
            let notice = res.data.data.info.notice
            this.errorMsgList = []
            this.errorMsgListTable = []
            this.isImportGoodsLoading = false
            this.uploadSuccessNoticeMsg = notice
            this.excel_check_id = res.data.data.check_result.id
            this.firstClassifyAdd = notice.firstClassifyAdd
            this.noneSystemMedicineList = notice.noneSystemMedicineList
            this.secondClassifyAdd = notice.secondClassifyAdd

            let tempObj = {
              row: '',
              bar_code: 'upc码',
              first_classify: '一级分类',
              is_shop: '状态',
              second_classify: '二级分类',
              selling_prise: '售价',
              sort: '排序',
              stock: '库存',
              store: '店铺',
              upc: 'upc码'
            }
            if(this.noneSystemMedicineList.length>0){
              this.noneSystemMedicineList.forEach(item => {
                this.exportNoneSystemMedicineList.push(item)
              })
            }
            this.exportNoneSystemMedicineList.unshift(tempObj)

            this.$store.state.uploadGoodsShow = false //先将组件关闭掉
          }else {
            this.errorMsgList = res.data.data.error_message
            this.errorMsgListTable = this.errorMsgList.slice(0,this.errorLimit)
            this.errorTotal = this.errorMsgList.length
            this.successMsg = ""
            // this.showuploadBtn = true
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          console.error(err)
          this.$message.error("导入失败")
        }).finally(msg => {
          this.isCheckExcel = false
        });

      },

      //确认导入数据
      async importGoods() {
        if(this.isImportGoodsLoading){
          return
        }
        clearInterval(this.interval) //先将之前的轮循关掉
        this.isImportGoodsLoading = true
        let params = {
          excel_check_id: this.excel_check_id,
          merchant_id: this.merchant_id
        }
        await this.$api.confirmImportStandardMedicine(params).then(res => {
          if(res.data.level=='success'){
            this.$message.success(res.data.message)
            this.uploadExcelDialog = false
            /*this.interval = setInterval(this.getImportStatus,1000);*/
            this.progress = ''
            /*this.$refs.importProgress.click()*/
            this.$store.state.excel_check_id = this.excel_check_id //存储导入Excel的文件到Vuex里
            this.$store.state.uploadGoodsShow = true
            this.$router.back()
          }else {
            this.$message.error(res.data.message)
            this.isImportGoodsLoading = false
          }
        }).catch(err => {
          /*this.$message.error("导入失败")*/
        }).finally(msg => {
          /*this.isImportGoodsLoading = false*/
        });

      },

      //获取导入状态
      async getImportStatus() {
        const res = await this.$api.getImportStatus({excel_check_id: this.excel_check_id}).then(res=>{
          if(res.data.level=='success'){
            let data = res.data.data
            this.progress = data.progress
            this.status_name = data.status_name
            if(data.is_success==1){
              this.isImportGoodsLoading = 3
              /*this.isShowUpload = false*/
              clearInterval(this.interval)
            } else {
              /*this.isShowUpload = true*/
            }
            this.isShowUpload = true
          }
        }).catch(err => {

        }).finally(msg => {

        });
      },

      //分页
      errorPageChange(e) {
        let start = (e - 1)*this.errorLimit
        let end = start + this.errorLimit
        this.errorMsgListTable = this.errorMsgList.slice(start,end)
      },

      output() {
        /* generate workbook object from table */
        let wb = XLSX.utils.table_to_book(document.querySelector("#mytable"));//mytable为表格的id名
        /* get binary string as output */
        let wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "非商品库商品列表.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      }

    }
  }
</script>

<style lang="scss" scoped>
  .contentFist {
    display: flex;
    /*justify-content: space-between;*/
    /*margin-top: 40px;*/
  }

  .detail{
    margin-top: 20px;
    font-size: 14px;
    line-height: 32px;
  }


  .title:last-child{
    /*margin-bottom: 20px;*/
  }

  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .detail{

  }

  .spanNum {
    width: 25px;
    height: 25px;
    line-height: 25px;
    margin-right: 15px;
    text-align: center;
    display: inline-block;
    border-radius: 50%;
    border: 1px solid black;
    .detail {
      font-size: 15px;
      margin-top: 10px;
      margin-left: 50px;
      color: #BBBBBB;
    }

    .btnLeft {
      margin-left: 50px;
    }
  }

  .upload-demo{
    margin-top: 10px;
  }

  .table-edit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .content {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .cell-icon {
      cursor: pointer;
      color: #3963bc;
      font-size: 16px;
    }

    .cell-icon-edit {
      display: flex;
      margin-left: 20px;
      width: 50px;
      justify-content: space-between;

      .cell-cancel {
        cursor: pointer;
        color: #3963bc;
        font-size: 16px;
      }

      .cell-save {
        cursor: pointer;
        color: #3963bc;
        font-size: 16px;
        margin-right: -20px;
      }
    }
  }

  .slide-enter-active{
    transition:all .3s linear;
  }
  .slide-leave-active{
    transition:all .3s linear;
  }
  .slide-enter{
    transform: translateX(100%);
    opacity: 0;
  }
  .slide-leave-to{
    transform: translateX(110%);
    opacity: 0;
  }

  .upload-process-btn{
    position: fixed;
    right: 3px;
    top: 100px;
    cursor: pointer;
  }

  .upload-process-container{
    /*position: fixed;
    right: 20px;
    top: 100px;*/
    /* background-color: #ffffff;*/
    width: 400px;
    /*min-height: 300px;*/
    /*transform-origin: center bottom;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    border: 1px solid #EBEEF5;*/
    .head-container{
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #EDEDED;
      .head-left{
        font-size: 15px;
        font-weight: bold;
      }
      .head-right{
        font-size: 18px;
        cursor: pointer;
        color: red;
      }
    }
    .message-list{
      .message-item{
        padding: 10px 5px;
        /*font-size: 14px;
        color: #333333;
        line-height: 20px;*/
      }
    }
  }

  .tip{
    padding: 0 10px;
    height: 40px;
    font-size: 11px;
    background-color: #00a0e9;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    border-radius: 15px 0 0 15px;
  }

</style>
<style scoped>

  /deep/.el-table td, /deep/.el-table th {
    text-align: left;
  }
  /deep/.el-table .warning-row {
    background: #f8f9fa;
  }

  /deep/.el-table .success-row {
    background: #ffffff;
  }
  /*/deep/.el_table_style{
    border: 1px solid #dee2e6;
  }
  /deep/.el-table td {
    border: none;
  }*/

  /deep/ .el-collapse-item__header{
    font-weight: bold;
  }

  /deep/ .el-collapse-item__content{
    text-align: left;
  }

</style>
